import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Card,
  Button,
  Form,
  Row,
  Col,
  Input,
  InputNumber,
  Spin,
  BackTop,
  notification,
  Icon,
  Popover,
  Affix,
} from 'antd';

import { refitFieldDecoratorOption, formatDatetime } from '../../../utils/tools';
import styles from './BasicInfo.less';

// const { TextArea } = Input;
const FormItem = Form.Item;
// const { MonthPicker } = DatePicker;

const fieldLabels = {
  bankName: '银行名称',
  creditCardNumber: '银行卡号',
  balance: '账户余额',
  score: '账户积分',
  experience: '升级经验值',
  createTime: '注册时间',
};

@connect(({ consumer, global, loading }) => ({
  consumer,
  global,
  loading: loading.models.consumer,
}))
@Form.create()
class BalanceInfo extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      // width: '100%',
      metaData: {},
      dataLoading: true,
      saving: false,
    };
  }

  componentDidMount() {
    this.isMountedFlag = true;

    const { match } = this.props;
    const { params } = match;
    const { id: consumerId } = params;

    this.loadData(consumerId);
  }

  loadData = id => {
    const { dispatch } = this.props;

    this.setState({ dataLoading: true }, () => {
      dispatch({
        type: 'consumer/get',
        payload: {
          prodictid: id,
        },
      }).then(() => {
        if (this.isMountedFlag) {
          const {
            consumer: {
              data: { data },
            },
          } = this.props;

          this.setState({ dataLoading: false, metaData: data });
        }
      });
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    const {
      dispatch,
      form,
      location: { pathname },
    } = this.props;
    const { metaData } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        this.setState({ saving: true });
        const submitValue = values;
        submitValue.province = metaData.province;

        dispatch({
          type: 'consumer/updateBalanceInfo',
          payload: submitValue,
        }).then(() => {
          this.setState({ saving: false });
          const {
            consumer: { data },
          } = this.props;
          const { code, message: messageText } = data;
          if (code === 200) {
            notification.success({
              placement: 'bottomRight',
              message: '操作结果',
              description: '数据已经保存成功，请进行后续操作。',
            });
          } else {
            notification.error({
              placement: 'bottomRight',
              message: '操作结果',
              description: messageText,
            });
          }

          dispatch(
            routerRedux.replace({
              pathname: `${pathname.replace('/load/', '/update/')}`,
            })
          );
        });
      }
    });
  };

  buildFieldDescription = (v, op, other) => {
    const o = (other || '') === '' ? '' : `,${other}`;
    return `请${op || '输入'}${v}${o}!`;
  };

  handleFormReset = () => {
    const { dispatch, form } = this.props;
    form.resetFields();
    dispatch({
      type: 'consumer/get',
      payload: {},
    }).then(() => {
      const {
        consumer: { data },
      } = this.props;
      this.setState({ metaData: data });
      this.setState({ saving: false });
    });
  };

  getErrorInfo = () => {
    const {
      form: { getFieldsError },
    } = this.props;
    const errors = getFieldsError();
    const errorCount = Object.keys(errors).filter(key => errors[key]).length;
    if (!errors || errorCount === 0) {
      return null;
    }
    const scrollToField = fieldKey => {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
      if (labelNode) {
        labelNode.scrollIntoView(true);
      }
    };
    const errorList = Object.keys(errors).map(key => {
      if (!errors[key]) {
        return null;
      }
      return (
        <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
          <Icon type="cross-circle-o" className={styles.errorIcon} />
          <div className={styles.errorMessage}>{errors[key][0]}</div>
          <div className={styles.errorField}>{fieldLabels[key]}</div>
        </li>
      );
    });
    return (
      <span className={styles.errorIcon}>
        <Popover
          title="表单校验信息"
          content={errorList}
          overlayClassName={styles.errorPopover}
          trigger="click"
          getPopupContainer={trigger => trigger.parentNode}
        >
          <Icon type="exclamation-circle" />
        </Popover>
        {errorCount}
      </span>
    );
  };

  // resizeFooterToolbar = () => {
  //   requestAnimationFrame(() => {
  //     const sider = document.querySelectorAll('.ant-layout-sider')[0];
  //     if (sider) {
  //       const width = `calc(100% - ${sider.style.width})`;
  //       const { width: stateWidth } = this.state;
  //       if (stateWidth !== width) {
  //         this.setState({ width });
  //       }
  //     }
  //   });
  // };

  validate = () => {
    const {
      form: { validateFieldsAndScroll },
      dispatch,
      location: { pathname },
    } = this.props;
    const { metaData } = this.state;

    validateFieldsAndScroll((error, values) => {
      if (!error) {
        this.setState({ saving: true });
        const submitValue = values;
        submitValue.province = metaData.province;

        dispatch({
          type: 'consumer/updateBalanceInfo',
          payload: submitValue,
        }).then(() => {
          const {
            consumer: { data },
          } = this.props;
          const { code } = data;
          if (code === 200) {
            notification.success({
              placement: 'bottomRight',
              message: '操作结果',
              description: '数据已经保存成功，请进行后续操作。',
            });
          }

          this.setState({ saving: false }, () => {
            dispatch(
              routerRedux.replace({
                pathname: `${pathname.replace('/load/', '/update/')}`,
              })
            );
          });
        });
      }
    });
  };

  render() {
    const { form } = this.props;
    const {
      metaData,
      saving,
      //  width,
      dataLoading,
    } = this.state;
    const { getFieldDecorator } = form;

    return (
      <Fragment>
        <div className={styles.containorBox}>
          <Card
            title="用户账户信息"
            className={styles.card}
            bordered={false}
            extra={
              <Affix offsetTop={20}>
                {this.getErrorInfo()}
                <Button
                  type="primary"
                  icon="save"
                  disabled={dataLoading}
                  // onClick={this.handleSaveBasicInfo}
                  onClick={this.validate}
                  loading={saving}
                >
                  保存
                </Button>
              </Affix>
            }
          >
            <Spin spinning={dataLoading || saving}>
              <Form layout="vertical">
                <Row gutter={24}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.bankName}>
                      {getFieldDecorator(
                        'bankName',
                        refitFieldDecoratorOption(metaData.bankName, metaData.bankName, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.bankName),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.bankName)} />)}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.creditCardNumber}>
                      {getFieldDecorator(
                        'creditCardNumber',
                        refitFieldDecoratorOption(
                          metaData.creditCardNumber,
                          metaData.creditCardNumber,
                          '',
                          {
                            rules: [
                              {
                                required: false,
                                message: this.buildFieldDescription(fieldLabels.creditCardNumber),
                              },
                            ],
                          }
                        )
                      )(
                        <Input
                          placeholder={this.buildFieldDescription(fieldLabels.creditCardNumber)}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.balance}>
                      {getFieldDecorator(
                        'balance',
                        refitFieldDecoratorOption(metaData.balance, metaData.balance, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.balance),
                            },
                          ],
                        })
                      )(
                        <InputNumber
                          style={{ width: '100%' }}
                          placeholder={this.buildFieldDescription(fieldLabels.balance)}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.score}>
                      {getFieldDecorator(
                        'score',
                        refitFieldDecoratorOption(metaData.score, metaData.score, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.score),
                            },
                          ],
                        })
                      )(
                        <InputNumber
                          style={{ width: '100%' }}
                          placeholder={this.buildFieldDescription(fieldLabels.score)}
                        />
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={24}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.experience}>
                      {getFieldDecorator(
                        'experience',
                        refitFieldDecoratorOption(metaData.experience, metaData.experience, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.experience),
                            },
                          ],
                        })
                      )(
                        <InputNumber
                          style={{ width: '100%' }}
                          placeholder={this.buildFieldDescription(fieldLabels.experience)}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={18} md={12} sm={24}>
                    <FormItem label={fieldLabels.createTime}>
                      {getFieldDecorator(
                        'createTime',
                        refitFieldDecoratorOption(metaData.createTime, metaData.createTime, '', {
                          rules: [
                            {
                              required: false,
                            },
                          ],
                        })
                      )(<span>{formatDatetime(metaData.createTime, 'YYYY-MM-DD HH:mm')}</span>)}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </Spin>
          </Card>
        </div>
        <BackTop />
      </Fragment>
    );
  }
}

export default BalanceInfo;
